package com.itheima.reggie.common;

//全局异常处理（因为如果每个地方抛异常都要写个try。。catch太麻烦了）

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

//拦截那些controller(拦截有RestController和Controller的注解)
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@ResponseBody
@Slf4j
public class GlobalExceptionHandler {

    //异常处理的方法，处理哪个异常（这个异常是处理sql保存时有相同的名字或者其他sql语句引起的错误）
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getMessage()); //Duplicate entry 'llisi' for key 'idx_username'

        if(ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");
            String msg = split[2] +"已存在";
           return   R.error(msg);
        }

        return R.error("未知错误");

    }


    @ExceptionHandler(CustomException.class)
    public R<String> exceptionHandler(CustomException ex){
        //这里可以拿到我们CategoryServiceImpl里面new出来的错误信息
        return R.error(ex.getMessage());
    }

}
